<template>
    <a-drawer 
      v-model:open="state.open" 
      placement="right" 
      width="35%"
      :closable="false"
      @close="handleCancle"
    >
      <template #title>
        <edit-title v-model="approvalConfig.name"/>
      </template>
      <div class="approval-drawer-content">
        <h3>审批类型</h3>
        <a-radio-group class="mb-5" v-model:value="approvalConfig.approvalType" @change="changeApprovalType">
          <a-radio :value="1">自动通过</a-radio>
          <a-radio :value="2">人工审批</a-radio>
        </a-radio-group>
        <div class="approval-editor" v-if="approvalConfig.approvalType == 2">
          <!-- 选择设置 -->
          <a-radio-group size="default" class="w-full flex mb-5" v-model:value="state.viewEditorType">
            <a-radio-button class="flex-1 text-center" :value="1">设置审批人</a-radio-button>
            <a-radio-button class="flex-1 text-center" :value="2">表单权限</a-radio-button>
            <a-radio-button class="flex-1 text-center" :value="3">操作权限</a-radio-button>
          </a-radio-group>
          <template v-if="state.viewEditorType == 1">
            <div class="approval-wrap mb-5">
              <div
                class="assignees-list"
              >
                <div class="assignees-title">
                  <h3>审批人设置</h3>
                </div>
                <div class="w-full p-3.5 assignees-content">
                  <a-radio-group class="w-full mb-2.5" v-model:value="approvalConfig.assigneeType" @change="changeItemAssigneeType">
                    <a-row class="mb-2">
                      <a-col :span="8"><a-radio :value="1">发起人本人</a-radio></a-col>
                      <a-col :span="8"><a-radio :value="2">部门负责人</a-radio></a-col>
                      <a-col :span="8"><a-radio :value="3">指定成员</a-radio></a-col>
                    </a-row>
                  </a-radio-group>
                  <!-- 部门负责人选择 -->
                  <div v-if="approvalConfig.assigneeType == 2" class="w-full mb-2.5">
                    <h3>请选择部门负责人</h3>
                    <setting-item-box name="发起人的" class="w-full">
                        <a-select
                          v-model:value="approvalConfig.layer"
                          placeholder="请选择部门负责人"
                          allowClear
                      >
                        <a-select-option 
                          v-for="i in 3"
                          :key="i"
                          :value="i - 1">
                          {{ i == 1 ? "直属部门负责人" : "直属部门负责人加 " + (i - 1) + " 级"  }}
                        </a-select-option>
                      </a-select>
                    </setting-item-box>
                  </div>
                  <!-- 指定成员 -->
                  <div v-if="approvalConfig.assigneeType == 3">
                    <h3>请选择成员</h3>
                    <a-button @click="openSelectUser" class="mr-2">
                      <div class="pr-2.5 pl-2.5">
                        <PlusOutlined/>
                      </div>
                    </a-button>
                    <a-tag v-for="user in approvalConfig.assignees" :key="user.id">
                      {{ user.realName }}
                    </a-tag>
                  </div>
                </div>
              </div>
            </div>
            <div class="approval-add mb-5">
              <!-- <a-button @click="addApprovalAssignee">添加审批人</a-button> -->
            </div>
            <!-- 会签、或签、序签 -->
            <div class="sign-type" v-if="Array.isArray(approvalConfig.assignees) && approvalConfig.assignees.length > 1">
              <h3>多人审批时采用的审批方式</h3>
              <a-radio-group class="mb-5" v-model:value="approvalConfig.multiInstanceApprovalType" >
                <a-radio :style="radioStyle" :value="1">会签（需所有审批人同意）</a-radio>
                <a-radio :style="radioStyle" :value="2">或签（一名审批人同意即可）</a-radio>
              </a-radio-group>
            </div>
            <div class="approval-null">
              <h3>审批人为空时</h3>
              <a-radio-group class="mb-5" v-model:value="approvalConfig.flowNodeNoAuditorType" >
                <a-radio :value="1">自动通过</a-radio>
                <a-radio :value="2">指定人员审批(若设置审批人则此项无效)</a-radio>
                <div v-if="approvalConfig.flowNodeNoAuditorType == 2">
                    <a-button @click="openSelectUser" class="mr-2">
                      <div class="pr-2.5 pl-2.5">
                        <PlusOutlined/>
                      </div>
                    </a-button>
                  <a-tag v-for="user in approvalConfig.assignees" :key="user.id">
                      {{ user.realName }}
                  </a-tag>
                </div>
              </a-radio-group>
            </div>
            <div class="approval-self">
              <h3>审批人与提交人为同一人时（只处理发起人本人情况）</h3>
              <a-radio-group class="mb-5 w-full" v-model:value="approvalConfig.flowNodeSelfAuditorType" >
                  <a-row class="mb-2">
                    <a-col :span="12"><a-radio :value="1">由发起人对自己审批</a-radio></a-col>
                    <a-col :span="12"><a-radio :value="2">自动跳过</a-radio></a-col>
                  </a-row>
                  <a-row>
                    <a-col :span="12"><a-radio :value="3">转交给部门负责人审批</a-radio></a-col>
                  </a-row>
              </a-radio-group>
            </div>
          </template>
          <template v-if="state.viewEditorType == 3">
            <div class="approval-opt-auth-setting ">
              <div class="check-box flex flex-col">
                <a-checkbox class="mb-3" v-model:checked="approvalConfig.assignable" >允许转交</a-checkbox>
                <a-checkbox class="mb-3" v-model:checked="approvalConfig.signable">允许加签 / 减签</a-checkbox>
              </div>
            </div>
          </template>
        </div>
      </div>
      <select-org-user ref="selectOrgUserRef" mode="multiple" @save="saveSelectedUser"/>
      <template #footer>
        <section class="flow-btn-box">
          <a-button @click="handleCancle">取消</a-button>
          <a-button type="primary" @click="save">保存</a-button>
        </section>
      </template>
    </a-drawer>
</template>

<script setup lang="ts">
import { computed, h, nextTick, reactive, ref, useTemplateRef } from 'vue';
import type { ApprovalNodeType, ApprovalProperties } from '../types';
import type LogicFlow from '@logicflow/core';
import editTitle from './editTitle.vue';
import settingItemBox from '@/components/chart/settingItemBox/index.vue'
import { PlusOutlined } from '@ant-design/icons-vue';
import selectOrgUser from '@/components/select-org-user/index.vue'
import { pick } from 'lodash';

const selectOrgUserRef = useTemplateRef('selectOrgUserRef')
// @ts-ignore
let approvalConfig = reactive<ApprovalProperties>({})
const curAssignee = ref({})
const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});
const state = reactive<{
  open:boolean,
  activeNode:ApprovalNodeType
  lf:LogicFlow | null,
  viewEditorType:number | null
}>({
  open: false,
  // @ts-ignore
  activeNode:null,
  lf:null,
  viewEditorType:1
})


const handleOpen = (node:ApprovalNodeType,lf:LogicFlow) => {
    state.open = true
    state.activeNode = node
    Object.assign(approvalConfig,node.properties)
    state.lf = lf
}

const handleCancle = ()=>{
  state.open = false
  approvalConfig = reactive({
    approvalType:1,
    assignable:true,
    signable:true,
    desc:"",
    assigneeType:1,
    layer:-1,
    assignees:[]
  })
  state.lf = null 
  state.activeNode = null
}

const save = ()=>{
  let desc = ""
  if(approvalConfig.approvalType == 2){
    if(approvalConfig.assigneeType == 1){
      desc = "发起人本人"
      if(approvalConfig.flowNodeSelfAuditorType == 1){
        desc += "（自审）"
      }else if(approvalConfig.flowNodeSelfAuditorType == 2){
        desc += "（自动通过）"
      }else if(approvalConfig.flowNodeSelfAuditorType == 3){
        desc += "（转交给部门负责人审批）"
      }
    }else if (approvalConfig.assigneeType == 2){
      desc = approvalConfig.layer == 0 ? "直属部门负责人" : "直属部门负责人加 " + (approvalConfig.layer) + " 级" 
    }else if(approvalConfig.assigneeType == 3){
      desc = approvalConfig.assignees.map(user=>user.realName).join(',')
    }
    // 若未设置审批人
    if(approvalConfig.assigneeType == null){
      if(approvalConfig.flowNodeNoAuditorType == 1){
        desc = "未设置审批人，自动通过" 
      }else if(approvalConfig.flowNodeNoAuditorType == 2){
        desc = approvalConfig.assignees.map(user=>user.realName).join(',')
      }
    }
  }else if(approvalConfig.approvalType == 1){
    desc = "自动通过"
  }
  desc  = "审批人:" + desc
  state.lf?.setProperties(
    state.activeNode.id,
    {
      ...approvalConfig,
      desc
    }
  )
  handleCancle()
}

const changeApprovalType = ()=>{
  if(approvalConfig.approvalType ==1 ){
    state.viewEditorType = 1
    approvalConfig.assignees = []
    approvalConfig.assigneeType = null
    approvalConfig.flowNodeNoAuditorType = undefined
    approvalConfig.flowNodeSelfAuditorType = undefined
  }else if(approvalConfig.approvalType == 2){
    state.viewEditorType = 1
    approvalConfig.assigneeType = null
    approvalConfig.flowNodeNoAuditorType = 1
    approvalConfig.flowNodeSelfAuditorType = 1
    if(!Array.isArray(approvalConfig.assignees)){
      approvalConfig.assignees = []
    }
  }
}

const openSelectUser = ()=>{
  const userIds = Array.isArray(approvalConfig.assignees) ? approvalConfig.assignees.map((item:any) => item.id) : []
  selectOrgUserRef.value?.handleOpen(userIds)
}
const saveSelectedUser = (users:any[])=>{
  approvalConfig.assignees = users
}

// 处理审批人类型改变
const changeItemAssigneeType = (e:any)=>{
  const valType = e.target.value
  if(valType == 1){
    // 发起人本人
    approvalConfig.assignees = []
    approvalConfig.layer = -1
  }else if(valType == 2){
    // 部门负责人
    approvalConfig.assignees = []
    approvalConfig.layer = 0
  }else if(valType == 3){
    // 指定成员
    approvalConfig.assignees = [] 
    approvalConfig.layer = -1
  }
  approvalConfig.multiInstanceApprovalType = null
}

defineExpose({
    handleOpen
})
</script>

<style lang='scss' scoped>
.flow-btn-box{
    display: flex;
    justify-content: end;
    gap: 12px;
}
.approval-drawer-content{
        overflow: auto;
        overflow-y: auto;
        scrollbar-gutter: stable;
        overflow-x: hidden;
        height: 100%;

        &::-webkit-scrollbar {
            width: 6px;
            background: transparent;
            opacity: 0;
            transition: opacity 0.3s;
        }

        &:hover::-webkit-scrollbar {
            opacity: 1;
        }

        &::-webkit-scrollbar-corner,
        &::-webkit-scrollbar-thumb,
        &::-webkit-scrollbar-track {
            border-radius: 4px;
        }

        &::-webkit-scrollbar-corner,
        &::-webkit-scrollbar-track {
            background-color: transparent;
        }

        &::-webkit-scrollbar-thumb {
            background-color: transparent;
        }

        &:hover::-webkit-scrollbar-thumb {
            background-color: #a19e9e;

            &:hover {
                background-color: #ccc;
            }
        }
  h3{
    font-weight: 650;
  }
  .approval-editor{
    .assignees-list{
      border:1px solid #ccc;
      border-radius: 15px;
      overflow: hidden;
      margin-bottom: 15px;
      .assignees-title{
          padding: 10px;
          width: 100%;
          height: 35px;
          background-color: #f5f6f7;
          border-top-left-radius: 15px;
          border-top-right-radius: 15px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          h3{

          }
      }
      .assignees-content{

      }
    }
  }
}
</style>